package com.tbit.uqbike.service.event.handler;

import com.tbit.config.tg.TbitAdminAccountInfo;
import com.tbit.uqbike.object.pojo.table.BrandTenantDO;
import com.tbit.uqbike.service.event.EventType;
import com.tbit.uqbike.webmanager.dao.core.BrandTenantDao;
import com.tbit.utils.DateTimeUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.tbit.business.auth.AuthConfig;
import org.tbit.business.resp.RespData;
import org.tbit.business.tenant.dto.UploadTenantDTO;
import org.tbit.business.tenant.service.TenantService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * 业务品牌信息变更时间处理器（同步统管平台）
 *
 * @author <a href="mailto:zhang.zhiliang@tbit.com.cn">Zhang ZhiLiang</a>
 * @version 1.0
 * @see <a href="http://adsl1.tbit.com.cn:21490/pages/viewpage.action?pageId=82182491">订单号规范</a>
 * @since 2025/5/27
 */
@Slf4j
@Component
@AllArgsConstructor
public class AccountChangeEventHandler extends EventHandler {
    private final TenantService tenantService;
    private final AuthConfig authConfig;
    private final BrandTenantDao brandTenantDao;

    @Override
    protected boolean match(Object config, EventType eventType) {
        if (Objects.isNull(config) || !(config instanceof TbitAdminAccountInfo)){
            return false;
        }
        return true;
    }

    @Override
    protected void doHandle(Object config, EventType eventType) {
        try {
            log.info("品牌信息变更事件：{},事件类型:{}",config,eventType);
            if (config instanceof TbitAdminAccountInfo){
                TbitAdminAccountInfo info = (TbitAdminAccountInfo) config;
                // 新增租户
                if (Objects.equals(EventType.ADD,eventType)){
                    UploadTenantDTO uploadTenantDTO = new UploadTenantDTO();
                    uploadTenantDTO.setUid(authConfig.getUid());
                    uploadTenantDTO.setSolutionCode("GX");
                    uploadTenantDTO.setName(info.getName());
                    uploadTenantDTO.setUploadTime(DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now()));
                    uploadTenantDTO.setRemark("共享平台创建租户同步");
                    RespData respData = tenantService.bindTenant(uploadTenantDTO, authConfig);
                    // 插入业务平台
                    if (respData.getCode() == 0){
                        brandTenantDao.insert(new BrandTenantDO(info.getAccountId(), respData.getData().toString(),null));
                    }
                }
                // 修改租户
                if (Objects.equals(EventType.UPDATE,eventType)){
                    // todo 统管平台暂时未对接修改租户
                }
                if (Objects.equals(EventType.DELETE,eventType)){
                    //todo 删除租户 不做处理 不能删统管数据
                }
            }
        } catch (Exception e) {
            log.error("推送统管品牌信息{}失败,业务类型{}",config,eventType,e);
        }
    }
}
